package com.hunliji.monitor.web.strategy.alert.handlers;

import com.alibaba.fastjson.JSON;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.service.api.AlertUserBindService;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.AlertUserBindBO;
import com.hunliji.monitor.service.api.model.bo.FeishuPostMessageBO;
import com.hunliji.monitor.service.api.model.bo.UserInfoBO;
import com.hunliji.monitor.service.api.model.param.AlertNotifyParam;
import com.hunliji.monitor.share.component.convertor.ConverterFacade;
import com.hunliji.monitor.share.enums.AlertActionTypeEnum;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.hunliji.monitor.web.model.param.AliyunAlertNotifyParam;
import com.hunliji.monitor.web.strategy.alert.AbstractAlertAction;
import com.hunliji.monitor.web.strategy.alert.model.AlertActionResultBO;
import com.hunliji.monitor.web.strategy.alert.model.AlertContext;
import com.hunliji.monitor.web.strategy.alert.util.TemplateUtil;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * File：FeishuChatAlertActionHandler.java<br> Title: <br> Description: <br>
 *
 * @author lejin Date: 2022/10/11
 */
@Slf4j
@Component
public class FeishuUserAlertActionHandler extends AbstractAlertAction {

    @Resource
    AlertUserBindService alertUserBindService;

    @Resource
    UserInfoService userInfoService;

    @Resource
    FeiShuManager feiShuManager;

    @Resource
    FeiShuFacade feiShuFacade;

    @Resource
    ConverterFacade converterFacade;

    @Override
    protected AlertActionTypeEnum getAlertActionType() {
        return AlertActionTypeEnum.FEISHU_USER;
    }

    @Override
    protected Boolean validate(AlertContext context) {
        return Boolean.TRUE;
    }

    @Override
    protected void doProcess(AlertContext context, AlertActionResultBO result) throws Exception {
        Long alertConfigId = context.getAlertConfigId();
        AliyunAlertNotifyParam aliyunAlertNotifyParam = context.getAliyunAlertNotifyParam();
        List<AlertUserBindBO> alertUserBindBOS = alertUserBindService.listByQuery(alertConfigId,
            null);
        if(CollectionUtils.isEmpty(alertUserBindBOS)){
            result.setSuccess(Boolean.FALSE);
            result.setErrorMsg("绑定userid为空");
            return;
        }
        List<Long> userInfoIds = alertUserBindBOS.stream().map(AlertUserBindBO::getUserInfoId)
            .collect(Collectors.toList());
        Map<Long, UserInfoBO> userInfoBOMap = userInfoService.getByIds(userInfoIds);
        String accessToken = feiShuFacade.getAccessToken();
        if(StringUtils.isEmpty(accessToken)){
            result.setSuccess(Boolean.FALSE);
            result.setErrorMsg("获取飞书token失败");
            return;
        }
        alertUserBindBOS.forEach(userInfo -> {
            Long userInfoId = userInfo.getUserInfoId();
            UserInfoBO userInfoBO = userInfoBOMap.get(userInfoId);
            if(Objects.isNull(userInfoBO) || StringUtils.isEmpty(userInfoBO.takeFeishuUserId())){
                result.setSuccess(Boolean.FALSE);
                result.setErrorMsg("用户id为空");
                return;
            }
            String feishuUserId = userInfoBO.takeFeishuUserId();
            String feishuUserIdType = userInfoBO.takeFeishuUserIdType();
            sendUserMessage(userInfo, aliyunAlertNotifyParam, feishuUserId, accessToken, ReceiveIdTypeEnum.getEnumByCode(feishuUserIdType));
        });
    }

    private void sendUserMessage(AlertUserBindBO alertUserBindBO, AliyunAlertNotifyParam aliyunAlertNotifyParam, String feiShuChatId, String accessToken, ReceiveIdTypeEnum receiveIdTypeEnum){
        String msgTemplate = alertUserBindBO.getMsgTemplate();
        if(StringUtils.isEmpty(msgTemplate)){
            FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(receiveIdTypeEnum.getCode())
                .receiveId(feiShuChatId)
                .content(JSON.toJSONString(FeishuPostMessageBO.getDefaultFeishuPostMessage(converterFacade.convert(aliyunAlertNotifyParam,
                    AlertNotifyParam.class), null)))
                .msgType(alertUserBindBO.getMsgType()).build();
            feiShuManager.sendMsg(param, accessToken);
        } else {
            String content = TemplateUtil.getConstantByTemplate(msgTemplate,
                aliyunAlertNotifyParam);
            FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(receiveIdTypeEnum.getCode())
                .receiveId(feiShuChatId)
                .msgType(alertUserBindBO.getMsgType())
                .content(content)
                .build();
            feiShuManager.sendMsg(param, accessToken);
        }
    }
}
